package com.dd.census.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dd.census.entity.SysRole;
import com.dd.census.entity.SysRoleMenu;
import com.dd.census.mapper.SysRoleMapper;
import com.dd.census.mapper.SysRoleMenuMapper;
import com.dd.census.service.SysRoleService;

@Service
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Autowired
	private SysRoleMenuMapper sysRoleMenuMapper;

	public Map<String, Object> selectPage(SysRole sysRole) {
		Map<String, Object> map = new HashMap<String, Object>();
		int total = sysRoleMapper.selectCount(sysRole);
		map.put("pageCount", Math.ceil((double) total / sysRole.getPageSize()));// 总页数
		map.put("total", total);// 总条数
		map.put("index", sysRole.getPageIndex());// 当前页
		if (total > 0) {
			sysRole.setPageIndex(sysRole.getPageSize() * (sysRole.getPageIndex() - 1));
			map.put("items", sysRoleMapper.selectPage(sysRole));
		}
		return map;
	}

	public SysRole selectById(Integer id) {
		return sysRoleMapper.selectById(id);
	}

	@Transactional
	public int insert(SysRole sysRole) {
		sysRoleMapper.insert(sysRole);

		// 同时添加角色菜单权限
		Integer srm = null;
		SysRoleMenu menu = new SysRoleMenu();
		for (int i = 0; i < sysRole.getMenu().size(); i++) {
			menu = new SysRoleMenu();
			srm = sysRole.getMenu().get(i);
			menu.setRoleId(sysRole.getId());
			menu.setMenuId(srm);
			sysRoleMenuMapper.insert(menu);
		}
		return sysRole.getId();
	}

	@Transactional
	public int update(SysRole sysRole) {
		int count = this.sysRoleMapper.update(sysRole);

		if (sysRole.getStatus() != 1) {
			// 先删除此角色的菜单权限
			SysRoleMenu srm = new SysRoleMenu();
			srm.setRoleId(sysRole.getId());
			sysRoleMenuMapper.deleteByRoleId(srm);
			
			// 同时添加新的角色权限
			for (int i = 0; i < sysRole.getMenu().size(); i++) {
				srm.setMenuId(sysRole.getMenu().get(i));
				srm.setRoleId(sysRole.getId());
				sysRoleMenuMapper.insert(srm);
			}
		}

		return count;
	}
}
